#include "RectangleBody.h"
#include <cmath>
#include <qmath.h>

RectangleBody::RectangleBody(float w, float h) {
	this->setId(rand());
	this->width = w;
	this->height = h;
}


void RectangleBody::calcAabb() {
	float angle = -(this->getAngle() / 180) * M_PI;
	Point position = *this->getPosition();
	float width = this->getWidth() / 2;
	float height = this->getHeight() / 2;

	Point p1(-width, height);
	Point p2(-width, -height);
	Point p3(width, -height);
	Point p4(width, height);

	float x1 = std::cos(angle) * p1.x() + std::sin(angle) * p1.y();
	float x2 = std::cos(angle) * p2.x() + std::sin(angle) * p2.y();
	float x3 = std::cos(angle) * p3.x() + std::sin(angle) * p3.y();
	float x4 = std::cos(angle) * p4.x() + std::sin(angle) * p4.y();

	float y1 = -std::sin(angle) * p1.x() + std::cos(angle) * p1.y();
	float y2 = -std::sin(angle) * p2.x() + std::cos(angle) * p2.y();
	float y3 = -std::sin(angle) * p3.x() + std::cos(angle) * p3.y();
	float y4 = -std::sin(angle) * p4.x() + std::cos(angle) * p4.y();

	float minX = std::min({ x1,x2,x3,x4 });
	float minY = std::min({ y1,y2,y3,y4 });
	float maxX = std::max({ x1,x2,x3,x4 });
	float maxY = std::max({ y1,y2,y3,y4 });
	Point  min(minX + position.x(), minY + position.y());
	aabb->setMin(min);
	Point max(maxX + position.x(), maxY + position.y());
	aabb->setMax(max);
	Point* points = new Point[4];
	points[0] = Point(x1 + position.x(), y1 + position.y());
	points[1] = Point(x2 + position.x(), y2 + position.y());
	points[2] = Point(x3 + position.x(), y3 + position.y());
	points[3] = Point(x4 + position.x(), y4 + position.y());
	aabb->setPoints(points);
	aabb->setPointSize(4);
	delete[] points;
}
